<?php

namespace api\home\controller;

use think\Db;
use think\Cache;
use think\Validate;
use api\common\controller\RestBaseController;
header('Content-type: text/html; charset=utf-8');

class BackController extends RestBaseController{

	public function getBack(){
	    //判断接口请求ip
        $allow =['47.56.198.23','47.52.74.208','47.75.84.211','47.100.222.220'];
        if(!empty($_SERVER["HTTP_CLIENT_IP"]) && !in_array($_SERVER["HTTP_CLIENT_IP"],$allow)){
            die();
        }
	    if(isset($_POST['accessKey'])){
			$str ="accessKey=".$_POST['accessKey']."&orderId=".$_POST['orderId']."&status=".$_POST['status'];
			$accessSecret = config('accessSecret');
			$sign = hash_hmac('sha1', $str, $accessSecret);
			if($_POST['status'] == '已成功' && $_POST['sign'] == $sign){
				//充值成功改变用户资产
				$order = Db::name('user_order')->where('order_no',$_POST['orderId'])->find();
				$user_info = Db::name('user')->where('id',$order['user_id'])->find();
				Db::startTrans();
				try{
					//改变资产
					$res = Db::name('user')->where('id',$order['user_id'])->setInc('static_wallet',$order['ipst']);
					//修改订单状态
					$res = Db::name('user_order')->where('order_no',$_POST['orderId'])->setField('order_status',4);
					//添加记录
					$log = [
						'user_id'=>$order['user_id'],
						'amount'=>$order['ipst'],
						'before'=>$user_info['static_wallet'],
						'after'=>$user_info['static_wallet'] + $order['ipst'],
						'type'=>1,
						'log_type'=>1,
                        'remark'=>'通道一充值',
						'source'=>7,
						'createtime'=>time(),
						'admin_remark'=>0
					];
					$res = Db::name('user_balance_log')->insert($log);
					if($res){
						echo 'success';
					}
					// 提交事务
					Db::commit();
				} catch (\Exception $e) {
					// 回滚事务
					Db::rollback();
					$this->error('充值失败');
				}

			}
			if($_POST['status'] == '已撤销' && $_POST['sign'] == $sign){
				//修改订单状态
				$res = Db::name('user_order')->where('order_no',$_POST['orderId'])->setField('order_status',5);
				if($res){
					echo 'success';
					$this->success('已撤销');
				}else{
					return false;
				}
			}
		}

		//拼多多支付
		if(isset($_POST["memberid"])){
			$returnArray = array( // 返回字段
				"memberid" => $_REQUEST["memberid"], // 商户ID
				"orderid" =>  $_REQUEST["orderid"], // 订单号
				"amount" =>  $_REQUEST["amount"], // 交易金额
				"datetime" =>  $_REQUEST["datetime"], // 交易时间
				"transaction_id" =>  $_REQUEST["transaction_id"], // 支付流水号
				"returncode" => $_REQUEST["returncode"],
			);
			$md5key = "9dehd3v14amttr0sf18z1914wi5aiflw";
			ksort($returnArray);
			reset($returnArray);
			$md5str = "";
			foreach ($returnArray as $key => $val) {
				$md5str = $md5str . $key . "=" . $val . "&";
			}
			$sign = strtoupper(md5($md5str . "key=" . $md5key));
            file_put_contents("success.txt",$sign, FILE_APPEND);
			if ($sign == $_REQUEST["sign"]) {
				if ($_REQUEST["returncode"] == "00") {
				    //充值成功改变用户资产
                    $order = Db::name('user_order')->where('trade_no',$_REQUEST["orderid"])->find();
                    //判断金额
                    if($_REQUEST["amount"] != $order['ipst']){
                        Db::name('user_order')->where('trade_no',$_REQUEST["orderid"])->setField('order_status',3);
                        $this->error('异常订单，请联系客服');
                    }
					$user_info = Db::name('user')->where('id',$order['user_id'])->find();
					Db::startTrans();
					try{
						//改变资产
						$res = Db::name('user')->where('id',$order['user_id'])->setInc('static_wallet',$order['ipst']);
						//修改订单状态
						$res = Db::name('user_order')->where('trade_no',$_REQUEST["orderid"])->setField('order_status',4);
						//添加记录
						$log = [
							'user_id'=>$order['user_id'],
							'amount'=>$order['ipst'],
							'before'=>$user_info['static_wallet'],
							'after'=>$user_info['static_wallet'] + $order['ipst'],
							'type'=>1,
							'log_type'=>1,
							'source'=>7,
                            'remark'=>'pdd充值',
							'createtime'=>time(),
							'admin_remark'=>0
						];
						$res = Db::name('user_balance_log')->insert($log);
						if($res){
							echo 'OK';
						}
						// 提交事务
						Db::commit();
					} catch (\Exception $e) {
						// 回滚事务
						Db::rollback();
						$this->error('充值失败');
					}
				}
			}
		}

	}
}
